<script setup>
import { Editor, Toolbar } from '@wangeditor-next/editor-for-vue'
// import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

// import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, shallowRef, onMounted, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/webStorage'
import { Boot } from '@wangeditor-next/editor'

// 获取host.js中的FILE_URL
const FILE_URL = hosts.FILE_URL[import.meta.env.MODE]

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  content: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '请输入内容...',
  },
})

const emit = defineEmits(['update:modelValue', 'update:content'])
const mode = ref('default')

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref(props.content || props.modelValue || '')

// 监听属性变化
watch(
  () => props.content,
  (newVal) => {
    if (editorRef.value && newVal !== editorRef.value.getHtml()) {
      editorRef.value.setHtml(newVal || '')
    }
  },
)

watch(
  () => props.modelValue,
  (newVal) => {
    if (editorRef.value && newVal !== editorRef.value.getHtml()) {
      editorRef.value.setHtml(newVal || '')
    }
  },
)

// 工具栏配置：插入自定义按钮
const toolbarConfig = {
  excludeKeys: ['fullScreen','group-more-style','group-indent','insertImage','insertVideo'],
  insertKeys: {
    index: 20,
    keys: ['uploadFile'],
  },
}

const editorConfig = {
  placeholder: props.placeholder || '请输入内容...',
  MENU_CONF: {
    codeSelectLang: { show: false }, // 隐藏语言选择
    uploadImage: {
      server: `${FILE_URL}/app/common/upload`,
      fieldName: 'Image',
      // 自定义插入图片
      customInsert(res, insertFn) {
        insertFn(res.result, '', '')
      },
    },
  },
  uploadVideo: {
    server: `${FILE_URL}/app/common/upload`,
    fieldName: 'Image',
    // 自定义插入视频
    customInsert(res, insertFn) {
      insertFn(res.result, '', '')
    },
  },
  uploadFile: {
    server: `${FILE_URL}/app/common/upload`,
    // 自定义插入附件
    customInsert(res, insertFn) {
      insertFn(res.result, '', '')
    },
  },
  // 设置默认的字体颜色和背景
  defaultContent: {
    color: '#333333',
    backgroundColor: 'transparent',
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  if (props.content || props.modelValue) {
    editor.setHtml(props.content || props.modelValue)
  }
}

// ---------------- 自定义“附件”上传菜单 ----------------
class UploadAttachmentMenu {
  constructor() {
    this.title = '附件'
    this.tag = 'button'
  }
  getValue(editor) {
    return ''
  }
  isActive(editor) {
    return false
  }
  isDisabled(editor) {
    return false
  }
  exec(editor) {
    // 创建隐藏的文件选择器
    const input = document.createElement('input')
    input.type = 'file'
    input.style.display = 'none'
    document.body.appendChild(input)

    input.onchange = async (e) => {
      const file = e.target.files && e.target.files[0]
      if (!file) return

      // 校验大小（≤50MB）
      if (file.size > 50 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过50MB')
        document.body.removeChild(input)
        return
      }

      try {
        const formData = new FormData()
        formData.append('Image', file)

        const res = await fetch(`${FILE_URL}/app/common/upload`, {
          method: 'POST',
          headers: {
            token: getToken() || '',
          },
          body: formData,
        })

        if (!res.ok) throw new Error('上传失败')
        const data = await res.json()
        if (data.code !== 0 || !data.result) throw new Error(data.msg || '上传失败')

        const fileUrl = data.result
        const fileName = file.name

        // 将超链接插入到编辑器
        editor.dangerouslyInsertHtml(
          `<a href="${fileUrl}" target="_blank" rel="noopener noreferrer" style="text-decoration: underline;
    color: #16437C;">${fileName}</a>`,
        )
        ElMessage.success('附件上传成功')
      } catch (err) {
        console.error('附件上传错误:', err)
        ElMessage.error('附件上传失败')
      } finally {
        document.body.removeChild(input)
      }
    }

    input.click()
  }
}

const myMenuConf = {
  key: 'uploadFile',
  factory() {
    return new UploadAttachmentMenu()
  },
}

let customRegistered = false
onMounted(() => {
  if (!customRegistered) {
    try {
      Boot.registerMenu(myMenuConf)
      customRegistered = true
    } catch (e) {
      // 可能重复注册，忽略
      customRegistered = true
    }
  }
})
</script>

<template>
  <div class="rich-editor-container">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      style="height: 350px; overflow-y: hidden"
      :defaultConfig="editorConfig"
      :mode="mode"
      :value="content || modelValue"
      @onCreated="handleCreated"
      @onChange="
        (editor) => {
          const html = editor.getHtml()
          const text = editor.getText()
          if(text.trim()){
            emit('update:modelValue', html)
            emit('update:content', html)
          } else {
            emit('update:modelValue', '')
            emit('update:content', '')
          }
        }
      " />
  </div>
</template>

<style scoped lang="scss">
.rich-editor-container {
  background-color: #ffffff;
  border-radius: 4px;
  border: 1px solid #e4e7ed;

  :deep(.w-e-text-container) {
    background-color: #ffffff;
  }

  :deep(.w-e-text) {
    color: #333333;
    p {
      color: inherit;
    }
  }

  /* 链接样式：添加下划线 */
  :deep(.w-e-text a) {
    text-decoration: underline;
  }

  /* table 样式 */
  table {
    border-top: 1px solid #ccc;
    border-left: 1px solid #ccc;
  }
  table td,
  table th {
    border-bottom: 1px solid #ccc;
    border-right: 1px solid #ccc;
    padding: 3px 5px;
  }
  table th {
    border-bottom: 2px solid #ccc;
    text-align: center;
  }

  /* blockquote 样式 */
  blockquote {
    display: block;
    border-left: 8px solid #d0e5f2;
    padding: 5px 10px;
    margin: 10px 0;
    line-height: 1.4;
    font-size: 100%;
    background-color: #f1f1f1;
  }

  /* code 样式 */
  code {
    display: inline-block;
    *display: inline;
    *zoom: 1;
    background-color: #f1f1f1;
    border-radius: 3px;
    padding: 3px 5px;
    margin: 0 3px;
  }
  pre code {
    display: block;
  }

  /* ul ol 样式 */
  ul,
  ol {
    margin: 10px 0 10px 20px;
  }
  
}
</style>
<style>
 .rich-editor-container a{
    text-decoration: underline;
  }
  /* 隐藏代码语言选择菜单 */
[data-menu-key="codeSelectLang"] {
  display: none !important;
}
.rich-editor-container button{
  background: transparent!important;
  border: transparent!important;
}
</style>


